package com.gok.seasonmovie.filter;

import com.gok.seasonmovie.service.WeChatService;
import jakarta.annotation.Resource;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.sf.jsqlparser.parser.TokenMgrException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class AuthFilter implements Filter {

    @Resource
    private WeChatService weChatService;

    private List<String> excludedUrls;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludedUrlString = filterConfig.getInitParameter("excludedUris");
        if (excludedUrlString != null) {
            excludedUrls = Arrays.asList(excludedUrlString.split(","));
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String path = request.getRequestURI();

        if (isExcluded(path)) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("Authorization");
        System.out.println("token访问"+token);

        if (token == null || weChatService.isTokenExpired(token)) {
            System.out.println("token过期或为空");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//响应状态码
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":600,\"message\":\"token过期或为空\"}");
            return;
        }



        String ip = request.getRemoteAddr();
        String url = request.getRequestURL().toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        String date = sdf.format(d);

        System.out.printf("%s %s 访问了 %s%n", date, ip, url);

        filterChain.doFilter(request, response);
    }

    private boolean isExcluded(String path) {
        if (excludedUrls == null) {
            return false;
        }
        for (String excludedUrl : excludedUrls) {
            if (path.contains(excludedUrl.trim())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {

    }

}